package web_jdbc.dao;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.cj.jdbc.MysqlDataSource;
import web_jdbc.po.User;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
public class UserDao implements IUserDao{
    private ObjectMapper objectMapper = new ObjectMapper();
    private static String jdbcUrl = "jdbc:mysql://localhost:3306/web_jdbc?allowPublicKeyRetrieval=true&characterEncoding=utf8&useSSL=false";
    private static String username = "username";
    private static String password = "password";
    @Override
    public User selectUser(User user) {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl(jdbcUrl);
        ((MysqlDataSource)dataSource).setUser(username);
        ((MysqlDataSource)dataSource).setPassword(password);
        //2,建立连接
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            String query = "SELECT * FROM user WHERE username = ? AND password = ?";
            PreparedStatement statement = connection.prepareStatement(query);
            statement.setString(1, user.getUsername());
            statement.setString(2, user.getPassword());
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                User ret = new User();
                ret.setUsername(resultSet.getString("username"));
                ret.setPassword(resultSet.getString("password"));
                return ret;
            } else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
